package com.cmq.web_1.employeemanage;


import com.cmq.web_1.employeemanage.EmployeeDAO;
import com.cmq.web_1.employeemanage.EmployeeDAOImpl;
import com.cmq.web_1.employeemanage.Employee;
import com.cmq.web_1.employeemanage.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/employeemanage/*")
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private EmployeeDAO employeeDAO;
    private SimpleDateFormat dateFormat;

    public void init() {
        employeeDAO = new EmployeeDAOImpl();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        if (action == null) {
            action = "/list";
        }

        switch (action) {
            case "/list":
                listEmployees(request, response);
                break;
            case "/view":
                viewEmployee(request, response);
                break;
            case "/add":
                showAddForm(request, response);
                break;
            case "/edit":
                showEditForm(request, response);
                break;
            case "/delete":
                deleteEmployee(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/error/404.jsp");
                break;
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        if (action == null) {
            response.sendRedirect(request.getContextPath() + "/error/404.jsp");
            return;
        }

        switch (action) {
            case "/add":
                addEmployee(request, response);
                break;
            case "/edit":
                updateEmployee(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/employeemanage/404.jsp");
                break;
        }
    }

    private void listEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("employees", employeeDAO.getAllEmployees());
        request.getRequestDispatcher("/employeemanage/list.jsp").forward(request, response);
    }

    private void viewEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        request.setAttribute("employee", employeeDAO.getEmployeeById(id));
        request.getRequestDispatcher("/employeemanage/view.jsp").forward(request, response);
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/employeemanage/add.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        request.setAttribute("employee", employeeDAO.getEmployeeById(id));
        request.getRequestDispatcher("/employeemanage/edit.jsp").forward(request, response);
    }

    private void addEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        try {
            String name = request.getParameter("name");
            String department = request.getParameter("department");
            String position = request.getParameter("position");
            BigDecimal salary = new BigDecimal(request.getParameter("salary"));
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            Date hireDate = dateFormat.parse(request.getParameter("hireDate"));

            Employee employee = new Employee(name, department, position, salary, email, phone, hireDate, user.getId());
            boolean isAdded = employeeDAO.addEmployee(employee);

            if (isAdded) {
                request.setAttribute("message", "员工信息添加成功");
            } else {
                request.setAttribute("error", "员工信息添加失败");
            }

            listEmployees(request, response);
        } catch (ParseException | NumberFormatException e) {
            request.setAttribute("error", "输入数据格式错误");
            showAddForm(request, response);
        }
    }

    private void updateEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 实现代码略
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("/employeemanage/login");
            return;
        }

        try {
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String department = request.getParameter("department");
            String position = request.getParameter("position");
            BigDecimal salary = new BigDecimal(request.getParameter("salary"));
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            Date hireDate = dateFormat.parse(request.getParameter("hireDate"));

            Employee employee = new Employee();
            employee.setId(id);
            employee.setName(name);
            employee.setDepartment(department);
            employee.setPosition(position);
            employee.setSalary(salary);
            employee.setEmail(email);
            employee.setPhone(phone);
            employee.setHireDate(hireDate);
            employee.setCreatedBy(user.getId()); // 保持创建人不变

            boolean isUpdated = employeeDAO.updateEmployee(employee);
            if (isUpdated) {
                request.setAttribute("message", "员工信息更新成功");
            } else {
                request.setAttribute("error", "员工信息更新失败");
            }
            listEmployees(request, response); // 更新后返回列表
        } catch (ParseException | NumberFormatException e) {
            request.setAttribute("error", "输入数据格式错误");
            showEditForm(request, response); // 错误返回编辑页
        }
    }

    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 实现代码略
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            boolean isDeleted = employeeDAO.deleteEmployee(id);
            if (isDeleted) {
                request.setAttribute("message", "员工信息删除成功");
            } else {
                request.setAttribute("error", "员工信息删除失败");
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "员工ID格式错误");
        }
        listEmployees(request, response); // 删除后返回列表
    }
}